package com.cuckoo.cuckoo_app2.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.PlatformApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.PlatformApi;
import com.cuckoo.cuckoo_app2.business.Imp.PlatformBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.SiteLinkBusinessImp;
import com.cuckoo.cuckoo_app2.business.PlatformBusiness;
import com.cuckoo.cuckoo_app2.business.SiteLinkBusiness;
import com.cuckoo.cuckoo_app2.dao.Platform;
import com.cuckoo.cuckoo_app2.dao.SiteLink;
import com.cuckoo.cuckoo_app2.dao.UserPlatformDao;
import com.cuckoo.cuckoo_app2.model.JavaScriptLoginModel;
import com.cuckoo.cuckoo_app2.model.JavaScriptParameterModel;
import com.cuckoo.cuckoo_app2.model.JavaScriptResponseModel;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.JavaScroptConsoleUtils;
import com.cuckoo.cuckoo_app2.utils.JavaScroptParameterUtils;
import com.cuckoo.cuckoo_app2.utils.MD5Utils;
import com.cuckoo.cuckoo_app2.utils.NetworkRequestHelperUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.quickjs.JSContext;
import com.quickjs.JSObject;
import com.quickjs.QuickJS;

import java.util.HashMap;
import java.util.Map;

public class LoginWebActivity extends AppCompatActivity {

    private String ID;
    private SiteLink siteLink;
    private Platform platform;
    private Gson gson;
    private Context context;
    ViewHolder holder;
    private PlatformBusiness platformBusiness = new PlatformBusinessImp();
    private SiteLinkBusiness siteLinkBusiness = new SiteLinkBusinessImp();
    private PlatformApi platformApi = new PlatformApiImp();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_web);
        this.context = this;
        this.gson = new Gson();
        holder = new ViewHolder();

        Intent intent = getIntent();
        ID = intent.getStringExtra("id");

        if (ID.equals(null) || ID.equals("")) {
            return;
        }

        siteLink = siteLinkBusiness.getByID(ID);
        if (siteLink == null) {
            return;
        }

        platform = platformBusiness.getById(ID);
        if (platform == null) {
            return;
        }

        holder.login_title.setText(platform.getTitle());

        // 绑定登录事件
        holder.login_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        LoginButton();
                    }
                }).start();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 登录按钮
     */
    public void LoginButton() {
        String username = holder.login_username.getText().toString();
        String password = holder.login_password.getText().toString();

        if (username.equals(null) || username.equals("") || password.equals(null) || password.equals("")) {
            return;
        }
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("username", username);
        bodyMap.put("password", password);
        bodyMap.put("url", siteLink.getLoginUrl());

        QuickJS quickJS = QuickJS.createRuntimeWithEventQueue();
        // 创建新的隔离
        JSContext contextParam = quickJS.createContext();
        // 创建新的隔离
        JSContext contextRespon = quickJS.createContext();
        try {
            contextParam.addJavascriptInterface(new MD5Utils(), "md5Utils");
            contextParam.addJavascriptInterface(new JavaScroptConsoleUtils(), "console");
            contextParam.addJavascriptInterface(new JavaScroptParameterUtils(bodyMap), "parameter");

            JSObject parameterObj = contextParam.executeObjectScript(siteLink.getLoginCodeBefore(), "script.js");
            JavaScriptParameterModel parameterModel = new JavaScriptParameterModel();
            parameterModel.setUrl(parameterObj.getString("url"));
            parameterModel.setMediaType(parameterObj.getString("mediaType"));
            parameterModel.setRequestType(parameterObj.getString("requestType"));
            parameterModel.setBody(parameterObj.getString("body"));
            parameterModel.setHeaders(parameterObj.getString("headers"));
            HashMap<String, String> headersMap = gson.fromJson(parameterModel.getHeaders(), HashMap.class);

            String response = "";
            if (parameterModel.getRequestType().equals("POST")) {
                response = NetworkRequestHelperUtils.postJson(
                        parameterModel.getUrl(),
                        parameterModel.getBody(),
                        headersMap
                );
            } else if (parameterModel.getRequestType().equals("GET")) {
                response = NetworkRequestHelperUtils.get(parameterModel.getUrl(), headersMap);
            }

            Log.i("TEST", "登录消息：" + response);
            Map<String, String> responseMap = new HashMap<>();
            responseMap.put("res", response);

            contextRespon.addJavascriptInterface(new JavaScroptParameterUtils(responseMap), "response");
            JSObject responseObj = contextRespon.executeObjectScript(siteLink.getLoginCodeAfter(), "script.js");

            JavaScriptLoginModel loginModel = new JavaScriptLoginModel();
            loginModel.setCode(responseObj.getString("code"));
            loginModel.setMessage(responseObj.getString("message"));
            loginModel.setToken(responseObj.getString("token"));
            loginModel.setParams(responseObj.getString("params"));

            if (!loginModel.getCode().equals("200")) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtils.showToast(context, loginModel.getMessage());
                    }
                });
                return;
            }
            platform.setToken(loginModel.getToken());
            platform.setIsLogin(1);
            platform.setParams(loginModel.getParams());

            // 保存
            platformBusiness.updata(platform);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    DialogUtils.showToast(context, loginModel.getMessage());
                }
            });

        } catch (Exception e) {
            Log.e("TEST", e.getMessage());
            DialogUtils.showToast(context, "服务请求失败");
        } finally {
            // 关闭js
            contextParam.close();
            contextParam = null;

            // 关闭js
            contextRespon.close();
            contextRespon = null;

            // 关闭引擎
            quickJS.close();
            quickJS = null;
            gson = null;
        }

        // 添加到云端
        platformApi.PlatformEditAsync(platform, new BaseCallbac<JsonObject>(){
            @Override
            public void onSuccess(JsonObject data) {
                runOnUiThread(()->{
                    if (!data.get("success").getAsBoolean()) {
                        DialogUtils.showToast(context, data.get("message").getAsString());
                        return;
                    }
                    DialogUtils.showToast(context, "成功");
                    // 暂停一秒
                    DialogUtils.sleep(1000);
                    // 返回上一页
                    finish();
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("TEST", "平台同步云失败");
            }
        });


    }

    /**
     * 获取相应的ID
     */
    class ViewHolder {
        TextView login_title;
        EditText login_username, login_password;
        Button login_button;

        public ViewHolder() {
            login_title = findViewById(R.id.login_title);
            login_username = findViewById(R.id.login_username);
            login_password = findViewById(R.id.login_password);
            login_button = findViewById(R.id.login_button);
        }
    }

}
